"""
@Project ：HD_project
@File    ：api_request.py
@IDE     ：PyCharm
@Author  ：靓仔
@Date    ：2023/11/18 0018 15:51
"""
from utils.http_utils import CustomRequests
import json
import requests
from utils.new_time import get_time_of_day, new_time


class ApiHd:
    def __init__(self):
        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Autothrowerror': 'true',
            'Connection': 'keep-alive',
            'Content-Length': '80',
            'Content-Type': 'application/json;charset=UTF-8',
            'Ctp-T-Code': '0002200000080659',
            'Host': '10.6.10.110',
            'Origin': 'http://10.6.10.110',
            'Ratio': '945*1512',
            'Referer': 'http://10.6.10.110/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                          'Chrome/119.0.0.0 Safari/537.36',
            'Cookie': 'userName=""; userPwd=""; cs_cStorage_=1; _isLogout=false; Authorization=""; province_flag=; access-token=eyJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50IjoieWFuemhpIiwidXNlcklkIjoiOEQzN0I2RkM0QUE4NDdCM0I0MDU1NDM1QjkyREVEQTEiLCJlbXBsb3llZUlkIjoiNzI3RkQyQTk5QkEwNDQ5MEI3QTcwNTcwQUVENDgxRkYiLCJlbXBsb3llZU5hbWUiOiLpopzlgLwiLCJvcmdJZCI6IjIwMDAwMDQ4Iiwib3JnQ29kZSI6IjIwMDAwMDQ4Iiwib3JnTmFtZSI6IuazleW-i-WQiOinhOmDqCIsInRoaXJkU3lzdGVtTmFtZSI6IkpBRFAiLCJzeXN0ZW1OYW1lIjoibnVsbCIsInN1YiI6IuminOWAvCIsImlhdCI6MTcwMTkxMDkzNiwiZXhwIjoxNzAxOTM4NjE3LCJyZWZyZXNoSW50ZXJ2YWwiOjQ1MCwianRpIjoiMmU0YTE4YzEtMWRhZi00ZmIwLWE2ODktMWE3YTU2MGM5ZjA2IiwicmVmcmVzaERhdGUiOjE3MDE5MTE2MTcwMDB9.U6xKWjzpZ-xl7nt_45GwFGfXDA1o9YmsAe0ls_tw_LVRB8DoU-wemhCPoauQ0XjWBE6q0JZcfTgHsVo3CkvH2A'
        }
        # self.user_login()
        # self.get_pant_info()

    # def user_login(self):
    #     _url = "http://10.6.10.110/jadp-api/auth/session"
    #     data = {"account": "huabao.tan", "password": "DZDR1M81FcALjaYAXpRv/nSA2kYcWRXemwE09Txa1AU="}
    #     response = requests.post(url=_url, json=data, headers=self.headers).text
    #     response_json = json.loads(response)
    #     token = response_json["result"]["token"]
    #     if token:
    #         self.headers["Cookie"] = 'access-token=' + token

    def get_pant_info(self):
        url = "http://10.6.10.110/zdgl-api/pub/bmhqdjs/repeat/xzbm"
        res = requests.get(url=url, headers=self.headers)
        return res

    # 新建年度计划接口
    def get_annual_plan_todo_id(self):
        url = "http://10.6.10.110/zdgl-api/common/data"
        data = {"xtbs": "10011006", "docType": "4",
                "data": {"primaryValue": None, "reason": None, "endDate": None, "hqr": None, "pageSize": 20,
                         "idList": None, "ngrq": None, "sfyhq": None, "templateId": "56F0B78C88934521A4A049701651300B",
                         "itemName": "", "pageNo": 1, "ngrName": None, "beginTime": None, "sortNames": [],
                         "cascadeSubQueryResult": None, "item": "制度计划", "cascadeSubQueryCondition": None,
                         "activityName": None, "updatorId": None, "bzbms": [
                        {"jgjb": "5", "orgStructureId": "CB0F6F1B7D534AF2BFAD00B40F9D514B", "zzjgxsfw": None,
                         "orgId4A": "20000048", "ffbmlzfs": None, "sfgkbm": "1", "orgLevel": 0, "orgId": "20000048",
                         "nameFullPath": "哈尔滨电气集团有限公司/哈电集团（本部）/法律合规部", "orgType": 7,
                         "jhzxbm": None, "children": [], "orgCode": "20000048", "fwdz": None, "orgProperty": 1,
                         "bmnbglld": None, "state": 1, "qzh": None, "orgName": "法律合规部", "corpId": "20000001",
                         "gwjhdwbm": None, "shortSpell": "flhgb", "deptId": "20000048", "sortNo": 0, "nblx": "2",
                         "sfgz": None, "sfcybmhq": None, "xsfw": None, "parentOrgId": "20000003", "simpleName": None,
                         "fullSpell": "falvheguibu", "fwjg": None, "sapHROrgId": None, "userId": "20000048",
                         "employeeName": "法律合规部"}], "ngbmName": "法律合规部", "_id": None, "flowStatus": None,
                         "tbjzTime": "2023-11-27", "thhj": None, "dwid": None, "creatorId": None, "remark": "1",
                         "sortTypes": [], "delFlag": None,
                         "title": "年度计划汇总（专用）" + str(get_time_of_day()) + "-测试数据", "searchText": None,
                         "docStatus": None,
                         "sqxz": "年度计划汇总（专用）", "ngr": None, "sortFields": [], "primaryName": "ID",
                         "updateTime": None, "url": None, "actionType": None, "beginDate": None, "createTime": None,
                         "cshqry": None, "sortType": "", "templateName": None, "ngbm": "20000048", "endTime": None,
                         "sortFieldName": None, "jsbzflList": [
                        {"yjbzfl": "1", "yjbzflName": "101标准化工作导则", "name": "101标准化工作导则", "code": "1",
                         "label": "101标准化工作导则", "value": "1"},
                        {"yjbzfl": "2", "yjbzflName": "102通用技术语言标准", "name": "102通用技术语言标准", "code": "2",
                         "label": "102通用技术语言标准", "value": "2"},
                        {"yjbzfl": "3", "yjbzflName": "103量和单位", "name": "103量和单位", "code": "3",
                         "label": "103量和单位", "value": "3"},
                        {"yjbzfl": "4", "yjbzflName": "104数值与数据", "name": "104数值与数据", "code": "4",
                         "label": "104数值与数据", "value": "4"},
                        {"yjbzfl": "5", "yjbzflName": "105互换性与精度标准及实现系列标准",
                         "name": "105互换性与精度标准及实现系列标准", "code": "5",
                         "label": "105互换性与精度标准及实现系列标准", "value": "5"}], "zddjList": [
                        {"primaryValue": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "dwid": "default", "code": "1",
                         "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                         "orderNum": 1, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                         "updateTime": "2023-11-11 16:15:33", "idList": None,
                         "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                         "createTime": "2023-02-23 08:59:30", "sortType": "", "pageNo": 1, "name": "基本管理制度",
                         "sortFields": [], "_id": None, "id": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "sortNames": [],
                         "sortFieldName": None, "label": "基本管理制度", "value": "1"},
                        {"primaryValue": "9CFE41DB5E3648D8A75E42F05C01F55E", "dwid": "default", "code": "2",
                         "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                         "orderNum": 2, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                         "updateTime": "2023-11-11 16:16:29", "idList": None,
                         "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                         "createTime": "2023-02-23 08:59:39", "sortType": "", "pageNo": 1, "name": "重要管理制度",
                         "sortFields": [], "_id": None, "id": "9CFE41DB5E3648D8A75E42F05C01F55E", "sortNames": [],
                         "sortFieldName": None, "label": "重要管理制度", "value": "2"},
                        {"primaryValue": "67E7B5193E094A5A858310FA1060D2BA", "dwid": "default", "code": "3",
                         "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                         "orderNum": 3, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                         "updateTime": "2023-11-11 16:16:38", "idList": None,
                         "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                         "createTime": "2023-02-23 08:59:58", "sortType": "", "pageNo": 1, "name": "一般管理制度",
                         "sortFields": [], "_id": None, "id": "67E7B5193E094A5A858310FA1060D2BA", "sortNames": [],
                         "sortFieldName": None, "label": "一般管理制度", "value": "3"}], "templateType": "4"}}


        # data = {"xtbs": "10011006", "docType": "4",
        #         "data": {"primaryValue": None, "reason": None, "endDate": None, "hqr": None, "pageSize": 20,
        #                  "idList": None, "ngrq": None, "sfyhq": None, "templateId": "0B4EA867A37642328CE17B16BE9CFE36",
        #                  "itemName": "", "pageNo": 1, "ngrName": None, "beginTime": None, "sortNames": [],
        #                  "cascadeSubQueryResult": None, "item": "制度计划", "cascadeSubQueryCondition": None,
        #                  "activityName": None, "updatorId": None, "bzbms": [
        #                 {"jgjb": "5", "orgStructureId": "CB0F6F1B7D534AF2BFAD00B40F9D514B", "zzjgxsfw": None,
        #                  "orgId4A": "20001078", "ffbmlzfs": None, "sfgkbm": None, "orgLevel": 0, "orgId": "20001078",
        #                  "nameFullPath": "哈尔滨电气集团有限公司/哈尔滨电气股份有限公司/电机公司/技术管理部",
        #                  "orgType": 7, "jhzxbm": None, "children": [], "orgCode": "20001078", "fwdz": None,
        #                  "orgProperty": 1, "bmnbglld": None, "state": 1, "qzh": None, "orgName": "技术管理部",
        #                  "corpId": "20000974", "gwjhdwbm": None, "shortSpell": "jsglb", "deptId": "20001078",
        #                  "sortNo": 0, "nblx": "2", "sfgz": None, "sfcybmhq": None, "xsfw": None,
        #                  "parentOrgId": "20000974", "simpleName": None, "fullSpell": "jishuguanlibu", "fwjg": None,
        #                  "sapHROrgId": None, "userId": "20001078", "employeeName": "技术管理部"}],
        #                  "ngbmName": "法律合规部", "_id": None, "flowStatus": None, "tbjzTime": "2023-11-30",
        #                  "thhj": None, "dwid": None, "creatorId": None, "remark": "1111111", "sortTypes": [],
        #                  "delFlag": None, "title": "年度计划汇总（专用）" + str(get_time_of_day()) + "-测试数据", "searchText": None, "docStatus": None,
        #                  "sqxz": "年度计划汇总（专用）", "ngr": None, "sortFields": [], "primaryName": "ID",
        #                  "updateTime": None, "url": None, "actionType": None, "beginDate": None, "createTime": None,
        #                  "cshqry": None, "sortType": "", "templateName": None, "ngbm": "20001008", "endTime": None,
        #                  "sortFieldName": None, "jsbzflList": [
        #                 {"yjbzfl": "1", "yjbzflName": "101标准化工作导则", "name": "101标准化工作导则", "code": "1",
        #                  "label": "101标准化工作导则", "value": "1"},
        #                 {"yjbzfl": "2", "yjbzflName": "102通用技术语言标准", "name": "102通用技术语言标准", "code": "2",
        #                  "label": "102通用技术语言标准", "value": "2"},
        #                 {"yjbzfl": "3", "yjbzflName": "103量和单位", "name": "103量和单位", "code": "3",
        #                  "label": "103量和单位", "value": "3"},
        #                 {"yjbzfl": "4", "yjbzflName": "104数值与数据", "name": "104数值与数据", "code": "4",
        #                  "label": "104数值与数据", "value": "4"},
        #                 {"yjbzfl": "5", "yjbzflName": "105互换性与精度标准及实现系列标准",
        #                  "name": "105互换性与精度标准及实现系列标准", "code": "5",
        #                  "label": "105互换性与精度标准及实现系列标准", "value": "5"}], "zddjList": [
        #                 {"primaryValue": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "dwid": "default", "code": "1",
        #                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
        #                  "orderNum": 1, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
        #                  "updateTime": "2023-11-11 16:15:33", "idList": None,
        #                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
        #                  "createTime": "2023-02-23 08:59:30", "sortType": "", "pageNo": 1, "name": "基本管理制度",
        #                  "sortFields": [], "_id": None, "id": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "sortNames": [],
        #                  "sortFieldName": None, "label": "基本管理制度", "value": "1"},
        #                 {"primaryValue": "9CFE41DB5E3648D8A75E42F05C01F55E", "dwid": "default", "code": "2",
        #                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
        #                  "orderNum": 2, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
        #                  "updateTime": "2023-11-11 16:16:29", "idList": None,
        #                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
        #                  "createTime": "2023-02-23 08:59:39", "sortType": "", "pageNo": 1, "name": "重要管理制度",
        #                  "sortFields": [], "_id": None, "id": "9CFE41DB5E3648D8A75E42F05C01F55E", "sortNames": [],
        #                  "sortFieldName": None, "label": "重要管理制度", "value": "2"},
        #                 {"primaryValue": "67E7B5193E094A5A858310FA1060D2BA", "dwid": "default", "code": "3",
        #                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
        #                  "orderNum": 3, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
        #                  "updateTime": "2023-11-11 16:16:38", "idList": None,
        #                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
        #                  "createTime": "2023-02-23 08:59:58", "sortType": "", "pageNo": 1, "name": "一般管理制度",
        #                  "sortFields": [], "_id": None, "id": "67E7B5193E094A5A858310FA1060D2BA", "sortNames": [],
        #                  "sortFieldName": None, "label": "一般管理制度", "value": "3"}], "templateType": "4"}}
        res = requests.post(url=url, json=data, headers=self.headers).text

        res_json = json.loads(res)
        if res_json["code"] == 200:
            todo_id = res_json["result"]["todoId"]
            return todo_id
        else:
            print(res_json)

    # 新建一个年度计划汇总待办
    def create_annual_plan(self):
        url = "http://10.6.10.110/zdgl-api/common/submit"
        # data = {"xtbs": "10011006", "docType": "4", "data": {"nextParticipantMap": {"zdgl_zdjh_nwzb_bmhq_user": [
        #     {"bllx": "2", "dblx": "bmhq|fqcshq", "id": "20000048", "name": "法律合规部", "role": "",
        #      "typeCode": "person"}]}, "nextActivityDefId": "zdgl_zdjh_nwzb_bmhq", "spyj": "同意。", "spjg": "1",
        #     "operateType": "1",
        #     "todoId": self.get_annual_plan_todo_id(), "sfyy": "2",
        #     "extend": "{\"bmhqList\":[{\"orgId\":\"20000048\",\"orgName\":\"法律合规部\",\"tzlx\":\"2\"}]}",
        #     "ywbs": "100", "sccldry": "", "pbzlc": ""}}
        data = {"xtbs": "10011006", "docType": "4", "data": {"nextParticipantMap": {"zdgl_zdjh_nwzb_bmhq_user": [
        {"bllx": "2", "dblx": "bmhq|fqcshq", "id": "20001078", "name": "技术管理部", "role": "",
         "typeCode": "person"}]}, "nextActivityDefId": "zdgl_zdjh_nwzb_bmhq", "spyj": "同意。", "spjg": "1",
        "operateType": "1",
        "todoId": self.get_annual_plan_todo_id(), "sfyy": "2",
        "extend": "{\"bmhqList\":[{\"orgId\":\"20000048\",\"orgName\":\"法律合规部\",\"tzlx\":\"2\"}]}",
        "ywbs": "100", "sccldry": "", "pbzlc": ""}}
        response = requests.post(url=url, json=data, headers=self.headers).json()
        if response["code"] == 200:
            print("新建待办完成！")

    # 获取当前账号下的年度汇总的待办数据
    def get_annual_summary_todo_data(self):
        url = "http://10.6.10.110/bd-grsx-api/todo/page/collapse"
        # data = {"bllx": "2", "userId": "68D37B6FC4AA847B3B4055435B92DEDA1", "xtbs": "10011006"}
        data = {"bllx": "2", "userId": "21364", "xtbs": "10011006"}
        try:
            response = requests.post(url=url, json=data, headers=self.headers)
            response.raise_for_status()  # 检查请求是否成功
            res = response.json()
            # 使用列表推导式提取所有待办事项的ID
            todo_ids = [a["id"] for result in res.get("result", []) for a in result.get("datas", {}).get("list", [])]
            return todo_ids
        except requests.exceptions.RequestException as e:
            print(f"Error in request: {e}")
            return []

    # 当前环节的id
    def get_plan_id(self):
        dic_list = []
        for id in self.get_annual_summary_todo_data():
            url = "http://10.6.10.110/bd-grsx-api/todo/queryTodoBytodoId/" + id
            res = json.loads(requests.post(url=url, headers=self.headers, json={}).text)
            dic_list.append(res["result"]["docId"])
        return dic_list

    # 当前待办下新增制度明细
    def institution(self, num: int):
        _num = 0
        for key in self.get_plan_id():
            for c in range(num):
                _num += 1
                url = "http://10.6.10.110/zdgl-api/institution"
                data = {"zbbmName": "法律合规部", "zbbm": "20000048", "item": "规章制度", "code": "无", "planType": "8",
                        "name": "制度计划明细" + get_time_of_day() + "_0" + str(c), "level": "1700102",
                        "zdxlbh": "170010202", "zdcj": "2",
                        "completeTime": str(new_time()), "trainingCompleteTime": str(new_time()),
                        "remark": "制度计划明细" + get_time_of_day() + "_0" + str(c),
                        "institutionRuleName": "制度计划明细" + get_time_of_day() + "_0" + str(c),
                        "planId": key, "bzbm": "20000048", "bzbmName": "法律合规部"}
                res = json.loads(requests.post(url=url, json=data, headers=self.headers).text)
                if res["code"] == 200:
                    print(f"{_num}:新增计划明细添加成功！")


if __name__ == '__main__':
    for a in range(3):
        ApiHd().create_annual_plan()
    ApiHd().institution(50)
